package team.lourd.network.system.own.repository.jpa.netel;

import com.querydsl.core.types.dsl.StringPath;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.data.querydsl.binding.QuerydslBinderCustomizer;
import org.springframework.data.querydsl.binding.QuerydslBindings;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RestResource;
import org.springframework.transaction.annotation.Transactional;
import team.lourd.network.system.own.domain.netel.NEBranch;
import team.lourd.network.system.own.domain.netel.QNEBranch;
import team.lourd.network.system.querydsl.ExtendedQuerydslJpaRepository;

import java.io.UnsupportedEncodingException;

public interface NEBranchRepository extends PagingAndSortingRepository<NEBranch, Long>, QuerydslBinderCustomizer<QNEBranch>, QuerydslPredicateExecutor<NEBranch>, ExtendedQuerydslJpaRepository<NEBranch,Long> {


    @RestResource(path = "branches", rel = "branches")
    @Query(value = "select * from ne_branch where ne_model_id=:nEModelId order by is_master desc", nativeQuery = true)
    Page<NEBranch> findById(@Param("nEModelId") long nEModelId, Pageable pageable);

    @RestResource(path = "master", rel = "master")
    @Query(value = "select * from ne_branch where ne_model_id=:nEModelId and is_master=:isMaster", nativeQuery = true)
    NEBranch findByDetailAndIsMaster(@Param("nEModelId") long nEModelId,@Param("isMaster") boolean isMaster);

    @Transactional
    @Query(value="update ne_branch set is_master=false where is_master=true and ne_model_id=:nEModelId", nativeQuery = true)
    @Modifying
    int updateMaster(@Param("nEModelId") long nEModelId);

    default void customize(QuerydslBindings bindings, QNEBranch model) {
        bindings.bind(String.class).first((StringPath path, String value) -> {
            // 中文乱码解决问题
            try {
                String newValue=new String(value.getBytes("iso-8859-1"),"utf-8");
                return  path.contains(newValue);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return  null;
            }
        });
    }
}